<template>
  <div>
    <el-card>
      <el-page-header title="成绩管理" @back="router.back()" style="margin-bottom: 20px">
        <template #content>
          <span class="text-large font-600 mr-3">成绩分析 — {{ courseData.coursename }}</span>
          <el-button style="margin-left: 550px" type="primary" :icon="Printer" @click="handlePrint">打印</el-button>
          <el-button style="margin-left: 20px" type="warning" :icon="Message" @click="handleMail">邮件通知</el-button>
        </template>
      </el-page-header>

      <div id="printarea">
        <el-row>
          <el-col :span="4">课程编号：{{ courseData.courseid }}</el-col>
          <el-col :span="4">课程名称：{{ courseData.coursename }}</el-col>
          <el-col :span="4">学分：{{ courseData.credit }}</el-col>
          <el-col :span="4">成绩类型：{{ courseData.type === 1 ? '百分制' : '等级划分制' }}</el-col>
          <el-col :span="4">专业名称：{{ courseData.major }}</el-col>
          <el-col :span="4">任课教师：{{ courseData.name }}</el-col>
        </el-row>

        <div style="margin: 20px" v-if="!isprint">
          <el-button style="height: 50px; margin-left: 10px; border: 0" @click="handleEcharts(barOption)">
            <el-icon size="50"><Histogram /></el-icon>
          </el-button>
          <el-button style="height: 50px; margin-left: 10px; border: 0" @click="handleEcharts(pieOption)">
            <el-icon size="50"><PieChart /></el-icon>
          </el-button>
          <el-button style="height: 50px; margin-left: 10px; border: 0" @click="handleEcharts(lineOption)">
            <el-icon size="50"><TrendCharts /></el-icon>
          </el-button>
        </div>

        <img :src="imgSrc" style="height: 600px; margin-top: 20px" v-if="isprint" />
        <div id="main" style="height: 600px; margin-top: 20px" v-else></div>

        <el-table :data="tableData" style="width: 100%" stripe v-loading="loading">
          <el-table-column prop="classes" label="班级" />
          <el-table-column prop="username" label="学号" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column label="平时成绩">
            <template #default="scope">
              <el-form-item style="margin: auto" v-if="num1">
                {{ scope.row.daily }}
              </el-form-item>
              <el-form-item style="margin: auto" v-else> — </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="实验成绩">
            <template #default="scope">
              <el-form-item style="margin: auto" v-if="num2">
                {{ scope.row.exp }}
              </el-form-item>
              <el-form-item style="margin: auto" v-else> — </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="期中成绩">
            <template #default="scope">
              <el-form-item style="margin: auto" v-if="num3">
                {{ scope.row.mid }}
              </el-form-item>
              <el-form-item style="margin: auto" v-else> — </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="期末成绩">
            <template #default="scope">
              <el-form-item style="margin: auto">
                {{ scope.row.final }}
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="courseid" label="总评">
            <template #default="scope">
              <div style="margin: auto" v-if="courseData.type === 1">
                {{ total(scope.row) }}
              </div>
              <div style="margin: auto" v-else>
                {{ level(scope.row) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="courseid" label="绩点">
            <template #default="scope">
              <div style="margin: auto; color: red; background-color: yellow" v-if="total(scope.row) < 60">0</div>
              <div style="margin: auto" v-else>
                {{ ((total(scope.row) - 50) / 10).toFixed(2) }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import { Histogram, PieChart, TrendCharts, Printer, Message } from '@element-plus/icons-vue'
import axios from 'axios'
import * as echarts from 'echarts'
const router = useRouter()
const route = useRoute()
const courseData = ref({})
const tableData = ref([])
const loading = ref(true)
const num1 = ref(0) //平时成绩
const num2 = ref(0) //实验成绩
const num3 = ref(0) //期中成绩
const num4 = ref(0) //期末成绩
const total = (data) => {
  data.daily = data.daily ? Number(data.daily) : 0
  data.exp = data.exp ? Number(data.exp) : 0
  data.mid = data.mid ? Number(data.mid) : 0
  data.final = data.final ? Number(data.final) : 0
  const sum = data.daily * num1.value + data.exp * num2.value + data.mid * num3.value + data.final * num4.value
  return sum / 10
}
const level = ({ final }) => {
  switch (final) {
    case 95:
      return '优秀'
      break
    case 85:
      return '良好'
      break
    case 75:
      return '中等'
      break
    case 65:
      return '及格'
      break
    case 0:
      return '不及格'
      break
  }
}
const barOption = {
  tooltip: {},
  xAxis: {
    data: ['不及格（0~59）', '及格（60~69）', '中等（70~79）', '良好（80~89）', '优秀（90~100）']
  },
  yAxis: {},
  series: [
    {
      name: '人数',
      label: {
        show: true,
        position: 'top'
      },
      type: 'bar',
      data: [0, 0, 0, 0, 0],
      animation: false
    }
  ],
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  }
}
const pieOption = {
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '人数',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 0, name: '不及格（0~59）' },
        { value: 0, name: '及格（60~69）' },
        { value: 0, name: '中等（70~79）' },
        { value: 0, name: '良好（80~89）' },
        { value: 0, name: '优秀（90~100）' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      animation: false
    }
  ],
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  }
}
const lineOption = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  xAxis: {
    type: 'category',
    data: ['不及格（0~59）', '及格（60~69）', '中等（70~79）', '良好（80~89）', '优秀（90~100）']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '人数',
      label: {
        show: true,
        position: 'top'
      },
      data: [0, 0, 0, 0, 0],
      type: 'line',
      animation: false
    }
  ],
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  }
}
// 不及格 及格 中等 良好 优秀
const chartsData = [0, 0, 0, 0, 0]
const isprint = ref(false)
const imgSrc = ref()

onMounted(async () => {
  await getCourseData()
  await getTableData()
  handleSetRatio()
  await handleChartsData()
  await handleEcharts(barOption)
})
const getCourseData = async () => {
  const res1 = await axios.get(`/api/course/list/${route.params.id}`)
  const res2 = await axios.get('/api/user/getteacherlist')
  // 将教师工号改为名字
  res1.data.data.forEach((item) => {
    res2.data.data.forEach((i) => {
      if (item['courseteacher'] === i['username']) {
        item['name'] = i['name']
      }
    })
  })
  courseData.value = res1.data.data[0]
}
const getTableData = async () => {
  const res1 = await axios.get(`/api/student/scorelist/${courseData.value.major}`)
  const res2 = await axios.get('/api/user/getstudentlist')
  const res3 = await axios.get(`/api/score/list/${courseData.value.courseid}`)
  // 附上学生名字
  res1.data.data.forEach((item) => {
    res2.data.data.forEach((i) => {
      if (item['username'] === i['username']) {
        item['name'] = i['name']
        item['email'] = i['email']
      }
    })
  })
  // 附上成绩信息
  res1.data.data.forEach((item) => {
    res3.data.data.forEach((i) => {
      if (item['username'] === i['username']) {
        Object.assign(item, i)
      }
    })
  })
  tableData.value = res1.data.data
  loading.value = false
}
const handleSetRatio = () => {
  if (courseData.value.ratio) {
    let arr = courseData.value.ratio.split(',')
    num1.value = Number(arr[0])
    num2.value = Number(arr[1])
    num3.value = Number(arr[2])
    num4.value = Number(arr[3])
  }
}
const handleEcharts = (Option) => {
  // 基于准备好的dom，初始化echarts实例
  // const myChart = echarts.init(document.getElementById('main'))

  //检测是否已经存在echarts实例，如果不存在，则不再去初始化
  let myChart = echarts.getInstanceByDom(document.getElementById('main'))
  //如果为空 则正常进行渲染 反之 不再进行初始化
  if (myChart == null) {
    myChart = echarts.init(document.getElementById('main'))
  } else {
    myChart.clear()
  }
  if (Option.series[0].type === 'pie') {
    Option.series[0].data = [
      { value: chartsData[0], name: '不及格（0~59）' },
      { value: chartsData[1], name: '及格（60~69）' },
      { value: chartsData[2], name: '中等（70~79）' },
      { value: chartsData[3], name: '良好（80~89）' },
      { value: chartsData[4], name: '优秀（90~100）' }
    ]
  } else {
    Option.series[0].data = chartsData
  }
  // 绘制图表
  myChart.setOption(Option)

  imgSrc.value = myChart.getDataURL()
}
const handleChartsData = () => {
  tableData.value.forEach((item) => {
    let score = total(item)
    if (score <= 100 && score >= 90) {
      return (chartsData[4] += 1)
    } else if (score <= 89 && score >= 80) {
      return (chartsData[3] += 1)
    } else if (score <= 79 && score >= 70) {
      return (chartsData[2] += 1)
    } else if (score <= 69 && score >= 60) {
      return (chartsData[1] += 1)
    } else if (score < 60) {
      return (chartsData[0] += 1)
    }
  })
}
const handlePrint = () => {
  isprint.value = true
  setTimeout(() => {
    document.body.innerHTML = document.getElementById('printarea').innerHTML
    window.print() //调用浏览器的打印功能打印指定区域
    window.location.reload()
    isprint.value = false
  }, 100)
}
const handleMail = async () => {
  // console.log(tableData.value)
  // console.log(courseData.value)

  for (let item of tableData.value) {
    await axios.post('/api/mail/send', {
      email: item.email,
      name: item.name,
      coursename: courseData.value.coursename,
      courseid: courseData.value.courseid
    })
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table .el-table__cell {
  text-align: center;
}
::v-deep .el-form-item__content {
  justify-content: center;
}
</style>
